package com.study.topic;

import java.util.HashMap;
import java.util.Map;

import com.study.publish.APublish;
import com.study.subscription.ISubscription;

/**
 * 主题容器类
 * 
 * @author donghuating
 *
 */
public class TopicContainer {

    private Map<String, APublish> topicContainer;

    public TopicContainer() {
        topicContainer = new HashMap<>();
    }

    /**
     * 增加一个topic订阅
     * 
     * @param topic
     * @param subscriptName
     * @return
     */
    public boolean addSubscript(String topic, ISubscription sub) {
        if (topicContainer.containsKey(topic)) {
            topicContainer.get(topic).add(sub);
            return true;
        }
        return false;
    }

    /**
     * 删除一个topic订阅
     * 
     * @param topic
     * @param subscriptName
     * @return
     */
    public boolean delSubscript(String topic, ISubscription sub) {
        if (topicContainer.containsKey(topic)) {
            APublish publish = topicContainer.get(topic);
            publish.delete(sub);
            return true;
        }
        return false;
    }

    public boolean addTopic(APublish publish) {
        if (!topicContainer.containsKey(publish.getName())) {
            topicContainer.put(publish.getName(), publish);
            return true;
        }
        return false;

    }

    /**
     * 发送消息
     * 
     * @param topicName
     * @param msg
     */
    public void sendMsg(String topicName, String msg) {
        for (String key : topicContainer.keySet()) {
            if (key.equals(topicName)) {
                topicContainer.get(key).send(msg);
            }
        }
    }

}
